package controller

import (
	apiserver "apedge/apiserver"
	"apedge/dto"

	"github.com/gin-gonic/gin"
)

func ApedgeNodeGroupRouter(r *gin.Engine) {
	group := r.Group("/api/v1/apedge/nodeGroup")

	group.GET("", dto.Wrapper(GetNodeGroupList))
	group.GET("/:id", dto.Wrapper(GetNodeGroupDetail))
	group.POST("", dto.Wrapper(CreateNodeGroup))
	group.DELETE("/:id", dto.Wrapper(DelNodeGroup))
}

func CreateNodeGroup(c *gin.Context) error {
	var err error
	var req dto.CreateNodeGroupReq
	var rsp dto.CreateNodeGroupRsp

	err = c.ShouldBindJSON(&req)
	if err != nil {
		return dto.ParameterError(c, err.Error())
	}
	userInfo, errRsp := PreHandler(c, &req)
	if errRsp != nil {
		return errRsp
	}

	id, err := apiserver.CreateNodeGroup(req, userInfo)
	if err != nil {
		logger.Errorln(err)
		return dto.ErrorToCodeRsp(c, err)
	}

	rsp = dto.CreateNodeGroupRsp{
		ID: id,
	}
	return dto.SuccessResp(c, rsp)
}

func GetNodeGroupList(c *gin.Context) error {
	var req dto.GetNodeGroupListReq
	var rsp dto.GetNodeGroupListRsp
	var err error

	var list []dto.OutApedgeNodeGroupItem
	var count int64

	err = c.ShouldBindQuery(&req)
	if err != nil {
		return dto.ParameterError(c, err.Error())
	}
	userInfo, errRsp := PreHandler(c, &req)
	if errRsp != nil {
		return errRsp
	}

	list, count, err = apiserver.GetNodeGroupList(req, userInfo)
	if err != nil {
		return dto.ErrorToCodeRsp(c, err)
	}

	rsp = dto.GetNodeGroupListRsp{
		Items: list,
		Total: count,
	}
	return dto.SuccessResp(c, rsp)
}

func GetNodeGroupDetail(c *gin.Context) error {
	var err error
	var req dto.GetNodeGroupDetailReq
	var rsp dto.GetNodeGroupDetailRsp

	err = c.ShouldBindUri(&req)
	if err != nil {
		return dto.ParameterError(c, err.Error())
	}
	_, errRsp := PreHandler(c, &req)
	if errRsp != nil {
		return errRsp
	}
	out, err := apiserver.GetNodeGroupDetail(req.ID)
	if err != nil {
		return dto.ErrorToCodeRsp(c, err)
	}

	rsp = dto.GetNodeGroupDetailRsp{
		OutApedgeNodeGroupItem: *out,
	}
	return dto.SuccessResp(c, rsp)
}

func DelNodeGroup(c *gin.Context) error {
	var err error
	var req dto.DelNodeGroupReq
	var rsp dto.DelNodeGroupRsp

	err = c.ShouldBindUri(&req)
	if err != nil {
		return dto.ParameterError(c, err.Error())
	}

	_, errRsp := PreHandler(c, &req)
	if errRsp != nil {
		return errRsp
	}

	err = apiserver.DelNodeGroup(req.ID)
	if err != nil {
		return dto.ErrorToCodeRsp(c, err)
	}

	return dto.SuccessResp(c, rsp)
}
